package com.chinaunicom.behavior.responsibilitychain;

import com.sun.istack.internal.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/6/8 15:09
 * Description: 构建执行器链
 */
public class HandlerExecutionChain {

    private Object handler = "testadmin";

    private Boolean flag;

    
    // 拦截器集合
    @Nullable
    private HandlerInterceptor[] interceptors;

    @Nullable
    private List<HandlerInterceptor> interceptorList;
    
    
    // 初始化 拦截器集合
    public List<HandlerInterceptor> initInterceptorList(){
        if (this.interceptorList == null){
            this.interceptorList = new ArrayList<>();
            // 将 interceptors 集合信息拷贝到 interceptorList集合中
            mergeArrayIntoCollection();
        }
        this.interceptors = null;
        return this.interceptorList;
    }

    // 添加拦截器
    public void addInterceptor(HandlerInterceptor interceptor){
        this.initInterceptorList().add(interceptor);
    }
    
    // 获取 interceptors
    public HandlerInterceptor[] getInterceptors(){
        if (this.interceptors == null && this.interceptorList != null){
            // 将 List 转成 Array
            this.interceptors = this.interceptorList.toArray(new HandlerInterceptor[0]);
        }
        return this.interceptors;
    }
    
    
    // 拦截器前置处理器
    public boolean applyPreHandler() {
        HandlerInterceptor[] interceptors = getInterceptors();
        if (interceptors != null && interceptors.length > 0){
            for (int i = 0; i < interceptors.length; i++) {
                // 获取拦截器对象
                HandlerInterceptor interceptor = interceptors[i];
                
                // 当 当前拦截器执行返回为 true 时才能继续执行下一个拦截器
                if (!interceptor.handler(this.handler)){
                    System.out.println("当前拦截器返回false，即程序中止。。。");
                    return false;
                }
            }
        }
        return true;
    }
    
    
    // 拦截器后置处理器
    public void applyPostHandler(){
        HandlerInterceptor[] interceptors = getInterceptors();
        if (interceptors != null && interceptors.length > 0){
            for (int i = 0; i < interceptors.length; i++) {
                HandlerInterceptor interceptor = interceptors[i];
                interceptor.postHandler(this.handler, null);
            }
        }
    }
    

    private void mergeArrayIntoCollection() {
        if (this.interceptors != null ){
            for (int i = 0; i <this.interceptors.length; i++) {
                this.interceptorList.add(this.interceptors[i]);
            }
        }
    }
}

